<script setup lang="ts" name="rangeSelecter">
import { ref, watch } from "vue";
import rangeOptions from "./range";
export interface Range {
  [key: string]: any;
}

let defaultModel: any = {};

for (const key in rangeOptions) {
  if (Object.prototype.hasOwnProperty.call(rangeOptions, key)) {
    defaultModel[key] = [];
  }
}
const props = defineProps(["modelValue"]);
const emit = defineEmits(["update:modelValue"]);

/**
 * 根据地区字符串生成各区域所包含的地区数组
 */
const setRangeByString = () => {
  let value: any = {};
  props.modelValue.split(",").map((r: any) => {
    for (const key in rangeOptions) {
      if (Object.prototype.hasOwnProperty.call(rangeOptions, key)) {
        const ranges = rangeOptions[key];
        if (ranges.includes(r)) {
          if (!value[key]) value[key] = [];
          value[key].push(r);
        }
      }
    }
  });
  return value;
};

const modelValue = props.modelValue ? setRangeByString() : defaultModel;
console.log(modelValue);

const handleChange = () => {
  //   console.log(checkedModel.value);
  setCheckAll();
  emitModel();
};
const emitModel = () => {
  const values = Object.values(checkedModel.value).flat();
  emit("update:modelValue", values.join(","));
};
const checkedModel = ref<Range>({});

//判断modelValue和初始值 各地区长度是否相等
const isSameLength =
  Object.values(modelValue).flat().length ==
  Object.values(rangeOptions).flat().length;

const setCheckAll = () =>
  (checkAll.value =
    Object.values(modelValue).flat().length ==
    Object.values(rangeOptions).flat().length);

const checkAll = ref<boolean>(isSameLength);

const onCheckAllChange = (e: any) => {
  checkedModel.value = e.target.checked ? rangeOptions : {};
  emitModel();
};
</script>

<template>
  <div class="rangeSelecter">
    <div class="absolute top-20px right-20px bg-blue-500 px-6px py-2px">
      <a-checkbox v-model:checked="checkAll" @change="onCheckAllChange">
        <span class="text-white">全选</span>
        <!-- {{ checkAll ? "取消" : "" }} -->
      </a-checkbox>
    </div>
    <a-form-item
      v-for="key in Object.keys(rangeOptions)"
      :key="key"
      :label="key"
      style="display: block"
    >
      <a-checkbox-group
        @change="handleChange"
        v-model:value="checkedModel[key]"
        :options="rangeOptions[key]"
      />
    </a-form-item>
  </div>
</template>

<style lang="less" scoped>
.rangeSelecter {
  width: 100%;
  padding: 20px 0;
  max-height: 200px;
  overflow: scroll;
  position: relative;
  &::-webkit-scrollbar {
    height: 0;
  }
}
</style>
